package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.Classify;
import com.chen.pfm.entity.DisplayBill;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.utils.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;
import java.util.Date;
import java.util.Random;


public class AddOneClassifySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "AddOneClassifySlice");
    ClassifyDBUtil dbUtil;
    Classify classify;
    TextField name;
    Text new_Classify_Icon_text;
    RadioButton radioButton;
    ListContainer listContainer;
    //1表示支出，4表示自定义类图标，000表示可以映射的图标
    int ctype_1;
    int ctype_3;
    //单选按钮
    RadioContainer container;
    //布局
    DirectionalLayout class_default;
    DirectionalLayout class_4_copper_0;
    DirectionalLayout class_4_copper_1;
    DirectionalLayout class_4_copper_2;
    DirectionalLayout class_4_copper_3;
    DirectionalLayout class_4_copper_4;
    int uid;
    ResultVo resultVo;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_add_one_classify);
        name = (TextField) findComponentById(ResourceTable.Id_classify_name);
        new_Classify_Icon_text = (Text) findComponentById(ResourceTable.Id_new_Classify_Icon_text);
        classify = new Classify();
        ctype_1 = 1;
        ctype_3 = 5;
        uid = Integer.valueOf(DataBaseUtil.GetValue(this, "uid"));
        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener(this::goBack);
        //默认
        class_default = (DirectionalLayout) findComponentById(ResourceTable.Id_class_default);
        class_default.setClickedListener((component) -> selectOneImage(component));
        setSelectedBg(class_default);
        //铜币0
        class_4_copper_0 = (DirectionalLayout) findComponentById(ResourceTable.Id_class_4_copper_0);
        class_4_copper_0.setClickedListener((component) -> selectOneImage(component));
        //铜币1
        class_4_copper_1 = (DirectionalLayout) findComponentById(ResourceTable.Id_class_4_copper_1);
        class_4_copper_1.setClickedListener((component) -> selectOneImage(component));
        //铜币2
        class_4_copper_2 = (DirectionalLayout) findComponentById(ResourceTable.Id_class_4_copper_2);
        class_4_copper_2.setClickedListener((component) -> selectOneImage(component));
        //铜币3
        class_4_copper_3 = (DirectionalLayout) findComponentById(ResourceTable.Id_class_4_copper_3);
        class_4_copper_3.setClickedListener((component) -> selectOneImage(component));
        //铜币4
        class_4_copper_4 = (DirectionalLayout) findComponentById(ResourceTable.Id_class_4_copper_4);
        class_4_copper_4.setClickedListener((component) -> selectOneImage(component));

        //确认按钮监听
        findComponentById(ResourceTable.Id_confirm_btn).setClickedListener((component) -> SaveData());

        //分类选择监听
        RadioContainer container = (RadioContainer) findComponentById(ResourceTable.Id_new_classify_RadioContainer);
        container.setMarkChangedListener((radioContainer, index) -> {
            // 可参考下方场景实例代码，自行实现
            if (index == 0) {
                ctype_1 = 1;
            } else if (index == 1) {
                ctype_1 = 2;
            } else if (index == 2) {
                ctype_1 = 3;
            }
        });
        //从本地数据库baseinfo中取得uid
        String uid = DataBaseUtil.GetValue(this, "uid");
        HiLog.info(LABEL, "从数据库中获得用户 uid = " + uid);
        classify.setUid(Integer.valueOf(uid));

    }

    private void goBack(Component component) {
        name.setText("");
        setSelectedBg(class_default);
        setUnSelectedBg(class_4_copper_0);
        setUnSelectedBg(class_4_copper_1);
        setUnSelectedBg(class_4_copper_2);
        setUnSelectedBg(class_4_copper_3);
        setUnSelectedBg(class_4_copper_4);
        new_Classify_Icon_text.setText("默认");
        //默认选择
        radioButton = (RadioButton) findComponentById(ResourceTable.Id_new_classify_default_option_1);
        if (radioButton != null) {
            radioButton.setChecked(true);
        }

        terminate();
    }

    //****************由于鸿蒙组件的单选按钮好像不能呈现九宫格的分布，简单粗暴点好了
    //自定义图表选择
    void setUnSelectedBg(Component component) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(Color.getIntColor("#ffffff")));
        element.setShape(ShapeElement.RECTANGLE);
        element.setCornerRadius(15);
        component.setBackground(element);
    }

    void setSelectedBg(Component component) {
        ShapeElement element = new ShapeElement();//4cf4c7
        //2022.4.21这里的颜色设置非常奇怪，个人怀疑颜色库有问题
        element.setRgbColor(new RgbColor(77, 172, 148, 100));
        element.setShape(ShapeElement.RECTANGLE);
        element.setCornerRadius(15);
        component.setBackground(element);
    }

    //选择一个自定义图标
    private void selectOneImage(Component component) {
        Text text = (Text) findComponentById(ResourceTable.Id_new_Classify_Icon_text);
        int cid = component.getId();

        switch (cid) {
            case ResourceTable.Id_class_default: {
                text.setText("默认");
                setSelectedBg(class_default);
                setUnSelectedBg(class_4_copper_0);
                setUnSelectedBg(class_4_copper_1);
                setUnSelectedBg(class_4_copper_2);
                setUnSelectedBg(class_4_copper_3);
                setUnSelectedBg(class_4_copper_4);

            }
            break;
            case ResourceTable.Id_class_4_copper_0: {
                ctype_3 = 0;
                text.setText("铜币0");
                setUnSelectedBg(class_default);
                setSelectedBg(class_4_copper_0);
                setUnSelectedBg(class_4_copper_1);
                setUnSelectedBg(class_4_copper_2);
                setUnSelectedBg(class_4_copper_3);
                setUnSelectedBg(class_4_copper_4);
            }
            break;
            case ResourceTable.Id_class_4_copper_1: {
                ctype_3 = 1;
                text.setText("铜币1");
                setUnSelectedBg(class_default);
                setUnSelectedBg(class_4_copper_0);
                setSelectedBg(class_4_copper_1);
                setUnSelectedBg(class_4_copper_2);
                setUnSelectedBg(class_4_copper_3);
                setUnSelectedBg(class_4_copper_4);
            }
            break;
            case ResourceTable.Id_class_4_copper_2: {
                ctype_3 = 2;
                text.setText("铜币2");
                setUnSelectedBg(class_default);
                setUnSelectedBg(class_4_copper_0);
                setUnSelectedBg(class_4_copper_1);
                setSelectedBg(class_4_copper_2);
                setUnSelectedBg(class_4_copper_3);
                setUnSelectedBg(class_4_copper_4);
            }
            break;
            case ResourceTable.Id_class_4_copper_3: {
                ctype_3 = 3;
                text.setText("铜币3");
                setUnSelectedBg(class_default);
                setUnSelectedBg(class_4_copper_0);
                setUnSelectedBg(class_4_copper_1);
                setUnSelectedBg(class_4_copper_2);
                setSelectedBg(class_4_copper_3);
                setUnSelectedBg(class_4_copper_4);
            }
            break;
            case ResourceTable.Id_class_4_copper_4: {
                ctype_3 = 4;
                text.setText("铜币4");
                setUnSelectedBg(class_default);
                setUnSelectedBg(class_4_copper_0);
                setUnSelectedBg(class_4_copper_1);
                setUnSelectedBg(class_4_copper_2);
                setUnSelectedBg(class_4_copper_3);
                setSelectedBg(class_4_copper_4);
            }
            break;
        }

    }
//***********************

    //保存数据到数据库
    private void SaveData() {

        classify.setCid(MyUtil.randomUUID());
        classify.setCtype(ClassifyDBUtil.getUniqueType(this, ctype_1, ctype_3, uid));
        classify.setCctime(DateUtils.getStrTimeFromDateTime(new Date()));
        //新曾的分类名称
        String cname = name.getText();
        if (cname == null || cname.equals("")) {
            MyToast.showMyToast(this, "分类名称不能为空！");
        } else {
            classify.setCname(cname);
            boolean exist = false;

            exist = ClassifyDBUtil.isExistByCnameAndCtype1(this, ctype_1, cname, uid);
            if (exist) {//
                MyToast.showMyToast(this, "分类标签已经存在！");
                return;

            } else {
                int create = ClassifyDBUtil.insertClassify(getContext(), classify);
                if (create > 0) {
                    MyToast.showMyToast(this, "本地分类标签保存成功！");
                    createRemoteDate(MyUtil.createClassify, classify);
                } else {
                    MyToast.showMyToast(this, "本地分类标签保存失败！");
                }

            }
        }

    }

    void createRemoteDate(String url, Object sendJsonObject) {
        //开一个线程更新用户信息
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            String getRequestjson = null;
            Gson gson = new Gson();
            String sendjson = gson.toJson(sendJsonObject);
            //转化为json
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, sendjson);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                HiLog.info(LABEL, "无法连接到网络！");
                //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                getUITaskDispatcher().asyncDispatch(() -> {
                            //在这里执行页面ui组件的显示刷新
                            MyToast.showMyToast(this, "无法连接到网络");
                        }
                );
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }
                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });
                    return;
                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                        if (resultVo.getCode() == 200) {
                            Intent intent = new Intent();
                            intent.setParam("cid", classify.getCid());
                            setResult(intent);
                            terminate();
                        }
                    });
                }
            }


        });
    }

    @Override
    protected void onActive() {
        HiLog.info(LABEL, "AddOneClassifySlice onActive");
        super.onActive();
    }

    @Override
    protected void onStop() {
        HiLog.info(LABEL, "AddOneClassifySlice onStop");
        super.onStop();

    }

    @Override
    protected void onBackground() {
        super.onBackground();
        HiLog.info(LABEL, "AddOneClassifySlice onBackground");
        goBack(null);
    }
}
